package ru.study.thinkin.chapter12;

import java.util.HashMap;
import java.util.Map;

class DynamicFieldsException extends Exception {

	public String getMessage() {
		return "сработал DynamicFiledsException " + super.getMessage();
	}
}

public class DynamicFields {
	private Map<String, Object> fields;

	public DynamicFields() {
		fields = new HashMap();
	}

	public String toString() {
		StringBuilder result = new StringBuilder();
		result.append("[");
		for (Map.Entry<String, Object> obj : fields.entrySet()) {
			result.append(obj.toString());
			result.append(";");
		}
		result.append("]");
		return result.toString();
	}

	public Object setField(String id, Object value)
			throws DynamicFieldsException {
		if (value == null) {
			DynamicFieldsException dfe = new DynamicFieldsException();
			dfe.initCause(new NullPointerException());
			throw dfe;
		} else {
			fields.put(id, value);
		}
		return value;
	}

	public Object updateField(String id, Object value)
			throws DynamicFieldsException {
		if (value == null) {
			DynamicFieldsException dfe = new DynamicFieldsException();
			dfe.initCause(new NullPointerException());
			throw dfe;
		} else {
			try {
				value = getField(id);
			} catch (NoSuchFieldException e) {
				throw new RuntimeException();
			}
			fields.put(id, value);
		}
		return value;
	}

	public Object getField(String id) throws NoSuchFieldException {
		if (!fields.containsKey(id)) {
			throw new NoSuchFieldException();
		}
		return fields.get(id);
	}

	public static void main(String[] args) {
		DynamicFields df = new DynamicFields();
		try {
			Object o = df.setField("ID", new Integer(7));
			o = df.setField("Name", null);
			o = df.updateField("QQ", 123);
			o = df.getField("QZ");
		} catch (NoSuchFieldException e) {
			e.printStackTrace(System.out);
		} catch (DynamicFieldsException e) {
			e.printStackTrace(System.out);
		}
		System.out.println(df.toString());
		System.out.println("finish");
	}

}
